package com.joplus.housekeeper.adapter;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.joplus.housekeeper.R;
import com.joplus.housekeeper.bean.GiftDependRulesBean;
import com.joplus.housekeeper.bean.GiftListBean;
import com.joplus.housekeeper.utils.CommonAdapter;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;
import com.joplus.housekeeper.utils.ViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/6.
 */
public class GiftAdapter extends CommonAdapter<GiftListBean.DataBean.CouponEntitiesBean> {


    private boolean flag = true;


    Context context;
    onGetSeclectddCouponsListener listener;


    List<GiftListBean.DataBean.CouponEntitiesBean> datas;

    private List<String> selectedPostion = new ArrayList<>();//用户选择的卡券的postion


    /**
     * 用户选择的数量
     */
    private int personCount = 0;


    /**
     * 礼券的数量限制
     */
    private int limitCount = 0;


    /**
     * 用户选择支付的产生的礼券依赖规则
     */
    GiftDependRulesBean rulesBean;


    /**
     * 当前选中的礼券的类型
     */
    private String currentSelectedType = "";


    /**
     * 不同类型的优惠券点击状态是否应该发生反转；
     */
    private Boolean isShouldReserval = false;


    private String lastType;//上次的种类
    private String lastCouponId;//上次选择的优惠券编码


    /**
     * @param context  上下文
     * @param layoutId 布局id
     * @param datas    数据
     */
    public GiftAdapter(Context context, int layoutId, List<GiftListBean.DataBean.CouponEntitiesBean> datas) {
        super(context, layoutId, datas);
        this.context = context;
        this.datas = datas;
    }

    public void setonGetSeclectddCoupons(onGetSeclectddCouponsListener listener) {
        this.listener = listener;
    }

    /**
     * 设置礼券的的使用数量限制
     */
    public void setPersonGiftDepondRules(GiftDependRulesBean rulesBean) {
        if (rulesBean == null) {
            return;
        }
        this.personCount = rulesBean.getQuality();
        this.rulesBean = rulesBean;
        flag = false;
        L.e("GiftAdapter-->" + "GiftDependRulesBean-->" + rulesBean.toString());
    }

    public void setCouponLimitCount(int limitCount) {
        this.limitCount = limitCount;
    }

    /**
     * 刷新数据
     *
     * @param datas
     */
    public void setNotifyDataSetChanged(List<GiftListBean.DataBean.CouponEntitiesBean> datas) {
        this.datas = datas;
        selectedPostion.clear();

        notifyDataSetChanged();

    }

    public List<GiftListBean.DataBean.CouponEntitiesBean> getData() {
        return datas;
    }

    @Override
    public void convert(ViewHolder holder, final GiftListBean.DataBean.CouponEntitiesBean listBean) {
        ImageView ivCoupon = holder.getView(R.id.iv_coupon);
        final View lowLight = holder.getView(R.id.view_lowlight);
        final ImageView isSelected = holder.getView(R.id.tv_isselected);

        TextView tvGiftName = holder.getView(R.id.tv_gift_name);
        TextView tvGiftCondition = holder.getView(R.id.tv_gift_condition);
        TextView tvGiftMoney = holder.getView(R.id.tv_gift_money);
        TextView tvGiftEndTime = holder.getView(R.id.tv_gift_end_time);
        ImageView iv_gift_label = holder.getView(R.id.iv_gift_label);


        StringUtils.setText(tvGiftName, listBean.getCouponName());

        StringUtils.setText(tvGiftEndTime, "截止日期 " + listBean.getExpirDate());
        tvGiftCondition.setText("满" + listBean.getConditionMoney() + "元可用");
        tvGiftMoney.setText("￥ " + listBean.getCouponMoney());


        String type = listBean.getCouponCategory();
        if (type.equals("free")) {
            ivCoupon.setImageResource(R.drawable.jo_gift_free_image);
            iv_gift_label.setImageResource(R.drawable.jo_git_label_free);
            tvGiftCondition.setText(listBean.getTagOne());
            tvGiftMoney.setText(listBean.getTagTwo());

        } else if (type.equals("use")) {
iv_gift_label.setImageResource(R.drawable.jo_gift_label_cash);
       //     ivCoupon.setImageResource(R.drawable.jo__gift_cashimage);
        }


        if (listBean.getCouponStatus().equals("10011") || listBean.getCouponStatus().equals("10013")
                || listBean.getCouponStatus().equals("10017")) {
            ivCoupon.setImageResource(R.drawable.jo_gift_list_no);
            iv_gift_label.setImageResource(R.drawable.jo_gift_label_no);
        } else if (listBean.getCouponStatus().equals("10013")) {
            ivCoupon.setImageResource(R.drawable.jo_gift_list_no);
            iv_gift_label.setImageResource(R.drawable.jo_gift_label_userd);
        }


        switch (listBean.getClicktype()) {
            case selected:
                isSelected.setVisibility(View.VISIBLE);
                lowLight.setVisibility(View.INVISIBLE);
                break;
            case normal:
                isSelected.setVisibility(View.INVISIBLE);
                lowLight.setVisibility(View.INVISIBLE);
                break;
            case reject:
                isSelected.setVisibility(View.INVISIBLE);
                lowLight.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }


//        //把选中的券的状态显示出来，防止滚动时界面复用造成view状态混乱
        if (isSelectedContainsCurrentType(listBean.getCouponId())) {
            isSelected.setVisibility(View.VISIBLE);
        }


        ivCoupon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!flag) {
                    //第一次点，之前没有记录用户的直接添加当前选中
                    if (selectedPostion.size() == 0) {

                        if (jugeCoupon(listBean)) {
                            selectedPostion.add(listBean.getCouponId());
                            lastType = listBean.getCouponCategory();
                            lastCouponId = listBean.getCouponId();

                            isShouldReserval = true;
                            //把不同类型的优惠券变灰
                            reversalGiftClickStatus(lastType, lastCouponId);
                            if (isShouldReserval) {
                                notifyDataSetChanged();
                            }
                            isShouldReserval = false;
                        }

                    } else {
                        //如果点过了，就去除
                        if (lastCouponId.equals(listBean.getCouponId())) {
                            isShouldReserval = true;
                            reversalGiftNormal(listBean.getCouponId());
                            if (isShouldReserval) {
                                notifyDataSetChanged();
                            }
                            isShouldReserval = false;

                            selectedPostion.clear();

                        } else {//上次点击的是满减券
                           if(lastType.equals("use")){
                               if(listBean.getCouponCategory().equals("use")){//这次也是满减
                                   T.showShort(context, "该券只能使用一张");
                               }else{//这次是体验券
                                   T.showShort(context, "礼券不能混用");

                                   isShouldReserval=true;
                                   reversalGiftClickStatus(listBean.getCouponCategory(),listBean.getCouponId());
                                   if (isShouldReserval) {
                                       notifyDataSetChanged();
                                   }
                                   isShouldReserval = false;
                                   selectedPostion.clear();
                               }

                           }else{//上次是体验券
                               if(listBean.getCouponCategory().equals("use")){//这次是满减券
                                   T.showShort(context, "礼券不能混用");
                                   isShouldReserval=true;
                                   reversalGiftClickStatus(listBean.getCouponCategory(),listBean.getCouponId());
                                   if (isShouldReserval) {
                                       notifyDataSetChanged();
                                   }
                                   isShouldReserval = false;
                                   selectedPostion.clear();

                               }else{//这次是体验券
                                   selectedPostion.add(listBean.getCouponId());
                                   reversalGiftClickStatus(listBean,selectedPostion);
                                   if (isShouldReserval) {
                                       notifyDataSetChanged();
                                   }
                                   isShouldReserval = false;

                                   lastType=listBean.getCouponCategory();
                                   lastCouponId=listBean.getCouponId();
                               }
                           }
                        }


                    }

                    reCallBack();
                    L.e("selectedPostion-->"+selectedPostion.toString());

                }

                L.e("GiftAdapter-->" + "GiftDependRulesBean-->" + "personCount-->" + personCount + "selectedPostion-->" + selectedPostion.size() + "listBean" + listBean.toString());

            }
        });

    }

    /**
     * 处理优惠券状态能否使用逻辑
     *
     * @param listBean
     */
    private Boolean jugeCoupon(GiftListBean.DataBean.CouponEntitiesBean listBean) {

        if (listBean.getCouponStatus().equals("10010") ||
                listBean.getCouponStatus().equals("10012") ||
                listBean.getCouponStatus().equals("10016")) {

            double m = Double.valueOf(listBean.getCouponMoney());
            double rm = Double.valueOf(rulesBean.getPrice());

            if (listBean.getCouponCategory().equals("free")) {
                if (selectedPostion.size() >= personCount) {
                    T.show(context, "所选卡券数超过支付人数", Toast.LENGTH_SHORT);
                    return false;

                } else if (selectedPostion.size() >= limitCount) {
                    T.show(context, "所选卡券数不能超过" + limitCount + "张限制", Toast.LENGTH_SHORT);
                    return false;
                } else {
                    return true;
                }
            } else {
                if (rm >= (int) m) {

                    if (selectedPostion.size() >= personCount) {
                        T.show(context, "所选卡券数超过支付人数", Toast.LENGTH_SHORT);
                        return false;

                    } else if (selectedPostion.size() >= limitCount) {
                        T.show(context, "所选卡券数不能超过" + limitCount + "张限制", Toast.LENGTH_SHORT);
                        return false;
                    } else {
                        return true;
                    }


                } else {

                    T.showShort(context, "不满足使用额度");
                    return false;
                }
            }


        } else {

            T.showShort(context, "礼券已失效");
            return false;
        }


    }


    /**
     * 调用用户选择后的回调接口
     */
    private void reCallBack() {
        if (listener != null) {
            List<GiftListBean.DataBean.CouponEntitiesBean> data = new ArrayList<>();
            for (GiftListBean.DataBean.CouponEntitiesBean d : datas) {
                if (selectedPostion.contains(d.getCouponId())) {
                    data.add(d);
                }
            }
            listener.getCoupons(data);
        }
    }


    /**
     * 用户选择的优惠券接口
     */
    public interface onGetSeclectddCouponsListener {
        public void getCoupons(List<GiftListBean.DataBean.CouponEntitiesBean> data);
    }


    /**
     * 修改不属于当前点中的优惠券的类型的显示状态
     *
     * @param type
     * @param couponId 优惠券Id
     */
    private void reversalGiftClickStatus(String type, String couponId) {


        for (GiftListBean.DataBean.CouponEntitiesBean b : datas) {
            if (b.getCouponCategory().equals(type) ) {

                if(b.getCouponId().equals(couponId)){
                    b.setClicktype(GiftListBean.GiftClickType.type.selected);
                }else{
                    b.setClicktype(GiftListBean.GiftClickType.type.normal);
                }



            } else {
                b.setClicktype(GiftListBean.GiftClickType.type.reject);
            }
        }


    }


    /**
     * 修改不属于当前点中的优惠券的类型的显示状态
     *
     * @param bean
     * @param couponIds
     */
    private void reversalGiftClickStatus(GiftListBean.DataBean.CouponEntitiesBean bean, List<String> couponIds) {


        for (GiftListBean.DataBean.CouponEntitiesBean b : datas) {
            if (b.getCouponCategory().equals(bean.getCouponCategory())) {

                if (couponIds.contains(bean.getCouponId())) {
                    b.setClicktype(GiftListBean.GiftClickType.type.selected);
                }
                else {
                    if(couponIds.contains(b.getCouponId())){
                        b.setClicktype(GiftListBean.GiftClickType.type.selected);
                    }

                }

            } else {
                b.setClicktype(GiftListBean.GiftClickType.type.reject);
            }
        }
        if (isShouldReserval) {
            notifyDataSetChanged();
        }
        isShouldReserval = false;

    }


    /**
     * 设置礼券状态为正常
     *
     * @param coupondId
     */
    private void reversalGiftNormal(String coupondId) {


        for (int i = 0; i < datas.size(); i++) {
            if (selectedPostion.contains(coupondId)) {
                L.e("GiftAdapter-->" + "reversalGiftNormal contains" + selectedPostion.toString());
                datas.get(i).setClicktype(GiftListBean.GiftClickType.type.normal);

                break;
            }
        }
        selectedPostion.remove(coupondId);
        if (isShouldReserval) {
            notifyDataSetChanged();
        }
        isShouldReserval = false;

    }

    /**
     * 选中的优惠券包含这个优惠券
     */
    private Boolean isSelectedContainsCurrentType(String type) {
        Boolean is = false;
        for (GiftListBean.DataBean.CouponEntitiesBean b : datas) {
            if (selectedPostion.contains(b.getCouponId()) && b.getCouponCategory().equals(type)) {
                is = true;
                break;
            }
        }
        return is;
    }

}
